################################
### R Function: fsQCA.random ###
################################

fsQCA.random=function(dataset, depvar, indepvars, min.freq, max.freq, random.reps, reps, explain, given.incl.cut0, given.incl.cut1, min){
  
  n.cut.list=c(min.freq:max.freq)
  
  fun.n.cut=function(x){
    dataset["random.variable"]=runif(n=nrow(dataset), min=0, max=1)
    out=as.data.frame(fsQCA.sim.inclcut(dataset=dataset, depvar=depvar, indepvars=c(indepvars, "random.variable"), n.cut=x, reps=reps, explain=explain, min=min))
    return(out)
  }
  
  fun.random=function(){
  out=lapply(X=n.cut.list, FUN=fun.n.cut)
  results=rbind.fill(out)
  return(results)}
  
  results=rdply(.n=random.reps, .expr=fun.random())
  
  Configurations=do.call(paste, as.data.frame(results[,5:ncol(results)], stringsAsFactors=FALSE))
  Configurations=gsub(pattern=" NA", replacement="", x=Configurations)
  Configurations=gsub(pattern=" ", replacement=" + \n  ", x=Configurations)

  results=cbind(results[,2:3], paste("Frequency Threshold = ", results[,4], sep=""), Configurations)
  colnames(results)[3]="n.cut"
  results$incl.cut1.val=as.numeric(as.vector(results$incl.cut1.val))
  results$incl.cut0.val=as.numeric(as.vector(results$incl.cut0.val))

  plot=ggplot(data=results, aes(x=incl.cut0.val, y=incl.cut1.val, colour=Configurations))+geom_point()+scale_color_hue(c=150, l=60)+xlim(0,1)+ylim(0,1)+xlab(label="Maximum Sufficiency Inclusion Score")+ylab(label="Minimum Sufficiency Inclusion Score")+geom_point(x=given.incl.cut0, y=given.incl.cut1, shape=17, color="black", size=2)+guides(col=guide_legend(keyheight=2))+facet_wrap(~n.cut, ncol=2)
  
  config=results$Configurations
  percent.pos=length(grep(pattern="RANDOM.VARIABLE", x=config, ignore.case=FALSE))/length(config)
  percent.neg=length(grep(pattern="random.variable", x=config, ignore.case=FALSE))/length(config)
  percent.all=length(grep(pattern="random.variable", x=config, ignore.case=TRUE))/length(config)
  
  return(list("results"=results, "plot"=plot, "percent.pos"=percent.pos, "percent.neg"=percent.neg, "percent.all"=percent.all))    

}

